package com.cliang.servlet;

import com.alibaba.fastjson.JSON;
import com.cliang.tools.db.DB;
import com.cliang.entity.Blog;
import com.cliang.tools.Tools;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class GetBlogListsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        HttpSession session=req.getSession();
        PrintWriter printWriter=resp.getWriter();
        List<Blog> blogList=new ArrayList<>();

        Connection conn= DB.getConnection();
        if(conn!=null){
            try {
                PreparedStatement psmt=conn.prepareStatement("select B_id,B_uid,B_tid,B_title,B_author,B_content,B_time from Blog.blog order by B_time desc limit 0,12");
                ResultSet rs=null;
                rs=psmt.executeQuery();
                if(rs!=null)while(rs.next()){
                    Blog blog=new Blog();
                    blog.setbId(rs.getInt("B_id"));
                    blog.setBuId(rs.getInt("B_uid"));
                    blog.setBtId(rs.getInt("B_tid"));
                    blog.setbTitle(rs.getString("B_title"));
                    blog.setbAuthor(rs.getString("B_author"));
                    blog.setbContent(Tools.getTextFromHtml(rs.getString("B_content"),50));
                    blog.setbTime(rs.getString("B_time"));
                    blogList.add(blog);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            DB.close(conn);
        }else {
            printWriter.write("加载数据有误！");
        }
        String json= JSON.toJSONString(blogList);
        printWriter.write(json);
        printWriter.close();
    }
}
